import tkinter as tk
from tkinter import ttk
from ui.BasePage import BasePage

class DataLoadingPage(BasePage):

    def __init__(self, parent, controller):
        super().__init__(parent, controller)

        """ 
            加载数据：逐条显示内容。
        """
        self.animation_index = 0
        self.animation_text = []
        self.animation_running = False
        # 需要加载显示的数据
        self.animation_text = [
            "数据加载中...\n",
            "数据加载完成！\n",
            "已加载以下数据集：\n",
            "-CWRU（0HP）\n",
            "总样本数：800 样本维度1024\n",
            "各类别样本数：\n",
            "-正常：200个样本\n",
            "-内圈故障：200个样本\n",
            "-外圈故障：200个样本\n",
            "-滚动体故障：200个样本"
        ]
        
        # 顶部功能按钮框架（保留原有设计）
        tab_frame = ttk.Frame(self.frame)
        tab_frame.pack(fill=tk.X, padx=5, pady=5)

        # 数据目录选择框架
        dir_frame = ttk.LabelFrame(self.frame, text="数据目录选择")
        dir_frame.pack(fill=tk.X, padx=10, pady=5)

        self.dir_entry = ttk.Entry(dir_frame, width=60)
        self.dir_entry.pack(side=tk.LEFT, padx=5, pady=5)
        self.dir_entry.insert(0, "D:/PHM2012/01/Bearing1_3")

        """ 
            路径选择Button
            "Info.TButton" 用于普通按钮
        """
        self.browse_btn = ttk.Button(dir_frame, text="浏览...", style="Info.TButton")
        self.browse_btn.pack(side=tk.LEFT, padx=5, pady=5)

        """ 
            数据集选择框架
        """
        dataset_frame = ttk.LabelFrame(self.frame, text="数据集选择")
        dataset_frame.pack(fill=tk.X, padx=10, pady=5)

        # 创建变量存储复选框状态
        self.cwru_var = tk.BooleanVar(value=True)  # CWRU主复选框默认选中
        self.hp_vars = {
            "0HP": tk.BooleanVar(value=True),  # 0HP默认选中
            "1HP": tk.BooleanVar(value=False),
            "2HP": tk.BooleanVar(value=False),
            "3HP": tk.BooleanVar(value=False),
        }

        self.phm_var = tk.BooleanVar(value=False)  # PHM主复选框默认未选中
        self.rpm_vars = {
            "1800rpm": tk.BooleanVar(value=False),
            "1650rpm": tk.BooleanVar(value=False),
            "1500rpm": tk.BooleanVar(value=False),
        }

        # 第一组复选框（CWRU）
        cwru_frame = ttk.Frame(dataset_frame)
        cwru_frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)

        # 创建一个内部框架来容纳主复选框和子选项
        cwru_inner_frame = ttk.Frame(cwru_frame)
        cwru_inner_frame.pack(side=tk.TOP, fill=tk.X)

        # 主复选框
        self.cwru_chk = ttk.Checkbutton(
            cwru_inner_frame,
            text="凯斯西储大学轴承数据（CWRU）马力选择：",
            variable=self.cwru_var,
        )
        self.cwru_chk.pack(side=tk.LEFT, padx=(0, 5))

        # 子选项复选框
        self.hp_0 = ttk.Checkbutton(
            cwru_inner_frame, text="0HP", variable=self.hp_vars["0HP"]
        )
        self.hp_0.pack(side=tk.LEFT, padx=2)

        self.hp_1 = ttk.Checkbutton(
            cwru_inner_frame, text="1HP", variable=self.hp_vars["1HP"]
        )
        self.hp_1.pack(side=tk.LEFT, padx=2)

        self.hp_2 = ttk.Checkbutton(
            cwru_inner_frame, text="2HP", variable=self.hp_vars["2HP"]
        )
        self.hp_2.pack(side=tk.LEFT, padx=2)

        self.hp_3 = ttk.Checkbutton(
            cwru_inner_frame, text="3HP", variable=self.hp_vars["3HP"]
        )
        self.hp_3.pack(side=tk.LEFT, padx=2)

        # 第二组复选框（PHM）
        phm_frame = ttk.Frame(dataset_frame)
        phm_frame.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)

        # 创建一个内部框架来容纳主复选框和子选项
        phm_inner_frame = ttk.Frame(phm_frame)
        phm_inner_frame.pack(side=tk.TOP, fill=tk.X)

        # 主复选框
        self.phm_chk = ttk.Checkbutton(
            phm_inner_frame, text="PHM2012数据集转速选择：", variable=self.phm_var
        )
        self.phm_chk.pack(side=tk.LEFT, padx=(0, 5))

        # 子选项复选框
        self.rpm_1800 = ttk.Checkbutton(
            phm_inner_frame, text="1800rpm", variable=self.rpm_vars["1800rpm"]
        )
        self.rpm_1800.pack(side=tk.LEFT, padx=2)

        self.rpm_1650 = ttk.Checkbutton(
            phm_inner_frame, text="1650rpm", variable=self.rpm_vars["1650rpm"]
        )
        self.rpm_1650.pack(side=tk.LEFT, padx=2)

        self.rpm_1500 = ttk.Checkbutton(
            phm_inner_frame, text="1500rpm", variable=self.rpm_vars["1500rpm"]
        )
        self.rpm_1500.pack(side=tk.LEFT, padx=2)

        """ 
            采样设置框架
        """
        sample_frame = ttk.LabelFrame(self.frame, text="采样设置")
        sample_frame.pack(fill=tk.X, padx=10, pady=5)

        self.sample_params = {}  # 存储采样参数控件
        params = [
            ("样本长度：", 1024, {"from_": 1, "to": 10000, "increment": 1}),
            ("步长：", 512, {"from_": 1, "to": 10000, "increment": 1}),
            ("重叠率：", 0.5, {"from_": 0.0, "to": 1.0, "increment": 0.05}),
            ("每类样本数：", 200, {"from_": 1, "to": 10000, "increment": 10}),
        ]

        for param, default, spinbox_opts in params:
            row_frame = ttk.Frame(sample_frame)
            row_frame.pack(fill=tk.X, padx=5, pady=2)

            # 参数标签
            ttk.Label(row_frame, text=param).pack(side=tk.LEFT, padx=2, pady=2)

            # 根据参数类型配置Spinbox
            if isinstance(default, float):
                # 浮点数参数
                spinbox = ttk.Spinbox(
                    row_frame,
                    from_=spinbox_opts["from_"],
                    to=spinbox_opts["to"],
                    increment=spinbox_opts["increment"],
                    format="%.2f",  # 保留两位小数
                    width=10,
                )
            else:
                # 整数参数
                spinbox = ttk.Spinbox(
                    row_frame,
                    from_=spinbox_opts["from_"],
                    to=spinbox_opts["to"],
                    increment=spinbox_opts["increment"],
                    width=10,
                )

            spinbox.pack(side=tk.LEFT, padx=2, pady=2, fill=tk.X, expand=True)
            spinbox.insert(0, default)
            self.sample_params[param] = spinbox

        """ 
            加载数据按钮
        """
        self.load_btn = ttk.Button(self.frame, text="加载数据", style="Info.TButton", command=self.start_animation)
        self.load_btn.pack(fill=tk.X, padx=10, pady=5)

        """ 
            信息显示文本框
        """
        self.info_text = tk.Text(self.frame, height=6, wrap=tk.WORD)
        # 初始化时清空文本框
        self.info_text.delete(1.0, tk.END)
        self.info_text.pack(fill=tk.X, padx=10, pady=5)
        self.info_text.config(state=tk.DISABLED)

    def start_animation(self):
        """开始文本动画显示"""
        if self.animation_running:
            return
            
        self.animation_running = True
        self.animation_index = 0
        
        # 清空文本框
        self.info_text.config(state=tk.NORMAL)
        self.info_text.delete(1.0, tk.END)
        
        # 启动动画
        self.continue_animation()
    
    def continue_animation(self):
        """继续动画，逐条添加文本"""
        if self.animation_index < len(self.animation_text):
            # 插入当前文本行
            self.info_text.insert(tk.END, self.animation_text[self.animation_index])
            self.animation_index += 1
            
            # 滚动到文本框底部
            self.info_text.see(tk.END)
            
            # 延迟一段时间后继续下一行
            self.info_text.after(300, self.continue_animation)
        else:
            # 动画完成，禁用文本框编辑
            self.info_text.config(state=tk.DISABLED)
            self.animation_running = False
    
    def get_selected_datasets(self):
        """获取用户选择的数据集"""
        selected = {
            "CWRU": {
                "0HP": self.hp_0.instate(["selected"]),
                "1HP": self.hp_1.instate(["selected"]),
                "2HP": self.hp_2.instate(["selected"]),
                "3HP": self.hp_3.instate(["selected"]),
            },
            "PHM": {
                "1800rpm": self.rpm_1800.instate(["selected"]),
                "1650rpm": self.rpm_1650.instate(["selected"]),
                "1500rpm": self.rpm_1500.instate(["selected"]),
            },
        }
        return selected

    def get_sampling_params(self):
        """获取采样参数"""
        params = {}
        for label, entry in self.sample_params.items():
            try:
                value = float(entry.get())
                if label == "重叠率：":
                    params[label] = max(0, min(1, value))  # 限制在0-1之间
                else:
                    params[label] = int(value) if value.is_integer() else value
            except ValueError:
                params[label] = None  # 无效输入
        return params